package cn.topevery.garden.dal.dao.impl;

import cn.topevery.garden.dal.dao.GreFileDao;
import cn.topevery.garden.dal.dao.HouseInfoDao;
import cn.topevery.garden.dal.dao.SituationDao;
import cn.topevery.garden.entity.dto.HouseInfoDTO;
import cn.topevery.garden.entity.po.GreFile;
import cn.topevery.garden.entity.po.HouseInfo;
import cn.topevery.garden.entity.po.Situation;
import cn.topevery.garden.entity.query.HouseInfoQuery;
import cn.topevery.garden.entity.vo.HouseInfoVO;
import cn.topevery.garden.framework.base.BaseDaoImpl;
import hw.topevery.framework.db.CommandType;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.db.entity.SqlQueryMate;
import hw.topevery.framework.db.entity.SqlUpdateMate;
import hw.topevery.framework.db.enums.ScriptConditionEnum;
import hw.topevery.framework.entity.DbCsp;
import hw.topevery.framework.entity.KeyValue;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 房屋信息表
 *
 * @author code-generate
 * @date 2022-02-14
 */
@Repository
public class HouseInfoDaoImpl extends BaseDaoImpl<HouseInfo> implements HouseInfoDao {
    @Autowired
    GreFileDao greFileDao;

    @Autowired
    SituationDao situationDao;

    @Override
    public <P extends DbCsp> List<HouseInfo> getSearch(P para) {
        return null;
    }


    @Override
    public DataPager<HouseInfoVO> listPage(HouseInfoQuery query) {
        String table = "t_house_info thi";

        String columns = "thi.*";

        int pageIndex = query.pageIndex - 1;
        int pageSize = query.pageSize;

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns).setOrderBy("thi.c_id desc");
        sqlQueryMate
                .where(true, "thi.c_db_status", ScriptConditionEnum.Eq, 0)
                .where(StringUtils.isNotBlank(query.getRecordStatus()), "thi.c_record_status", ScriptConditionEnum.Eq, query.getHouseholder())
                .where(StringUtils.isNotBlank(query.getHouseholder()), "thi.c_householder", ScriptConditionEnum.Like, query.getHouseholder())
                .where(StringUtils.isNotBlank(query.getLandCode()), "thi.c_land_code", ScriptConditionEnum.Like, query.getLandCode())
        ;

        return getDataPager(sqlQueryMate, pageSize, pageIndex, HouseInfoVO.class);
    }

    @Override
    public HouseInfo getEntityByColumn(String key, String value) {
        KeyValue<String> map = new KeyValue<>();
        map.key = key;
        map.value = value;
        return getEntityByColumnEqValue(map);
    }

    @Override
    public void commit(HouseInfoDTO dto, Integer userId) {
        boolean isUpdate = dto.getId() != null;
        LocalDateTime now = LocalDateTime.now();
        HouseInfo houseInfo = new HouseInfo();
        BeanUtils.copyProperties(dto, houseInfo);
//        if (CollectionUtils.isNotEmpty(dto.getMapRangesPoints())) {
//            houseInfo.setMapRanges(GeometryHelper.getGeometry(GeometryHelper.getWellKnownText(dto.getMapRangesPoints(), GeometryTypeEnum.PLANE)));
//            houseInfo.setGeoWkt(GeometryHelper.getWellKnownText(dto.getMapRangesPoints(), GeometryTypeEnum.PLANE));
//        }

        Situation situation = new Situation();
        situation.setHouseId(houseInfo.getHouseId());
        situation.setLandId(houseInfo.getLandCode());
        situation.setSituationId(UUID.randomUUID().toString());
        if (!isUpdate) {
            houseInfo.setDbStatus(true);
            houseInfo.setCreateId(userId.toString());
            houseInfo.setCreateTime(now);
//            houseInfo.setHouseId(UUID.randomUUID().toString());
            saveOrUpdate(userId.toString(), houseInfo);
            situation.setDesc("房屋信息新增");
        } else {
            //如果是修改，先删除旧的附件，再把新的附件保存
            greFileDao.deleteByMainId(dto.getId(), userId.toString(), 4);
            houseInfo.setCreateTime(now);
            houseInfo.setCreateId(userId.toString());
            saveOrUpdate(userId.toString(), houseInfo);
            situation.setDesc("房屋信息修改");
        }
        if (dto.getFileList() != null && !dto.getFileList().isEmpty()) {
            List<GreFile> collect = dto.getFileList().stream().peek(temp -> {
                temp.setDataType(4);
                temp.setCreateTime(now);
                temp.setCreateId(userId.toString());
                temp.setMainId(dto.getId());
                temp.setDbStatus(false);
            }).collect(Collectors.toList());
            for (GreFile greFile : collect){
                greFileDao.saveOrUpdate(userId.toString(),greFile);
            }
        }
//        if (houseInfo.getLat() != null && houseInfo.getLng() != null) {
//            updateMapRange(houseInfo.getHouseId(),houseInfo.getLat(), houseInfo.getLng());
//        }
        situationDao.saveOrUpdate(userId.toString(), situation);
    }

    private void updateMapRange(String id, Float lat, Float lng) {
        String sql = "update t_house_info\n" +
                "set c_map_ranges=ST_GeomFromText('point( "+ lat + " " + lng + " )',4326)\n" +
                "where c_house_id=" + id;
        run(sql, CommandType.Text, dbCommand -> {
            dbCommand.executeNonQuery();
        });
    }

    @Override
    public void deleteBatchById(String userId, Integer[] ids) {
        SqlUpdateMate sqlUpdateMate = new SqlUpdateMate("t_house_info thi");
        sqlUpdateMate.setColumnValue(true, "c_db_status", 1)
                .setColumnValue(true, "c_db_last_update_date", LocalDateTime.now())
                .setColumnValue(true, "c_db_last_update_id", Integer.valueOf(userId))
                .where(true, "c_id", ScriptConditionEnum.In, ids);
        run(sqlUpdateMate.getSql(), CommandType.Text, dbCommand -> {
            sqlUpdateMate.getParameters().forEach(dbCommand::addParameter);
            dbCommand.executeNonQuery();
        });
        List<HouseInfo> houseInfoList = getEntitys(ids);
        Situation situation = new Situation();
        for (HouseInfo houseInfo : houseInfoList) {
            situation.setHouseId(houseInfo.getHouseId());
            situation.setLandId(houseInfo.getLandCode());
            situation.setSituationId(UUID.randomUUID().toString());
            situation.setDesc("房屋信息删除");
        }
        situationDao.insert(userId, situation);
    }

    @Override
    public List<Map<String, Object>> getHouseIdList() {
        String sql = "select c_house_id houseId, c_land_code landCode from t_house_info";
        return getMap(sql);
    }
}
